/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */
package managed;

import domen.User;
import ejb.ApplicationFacade;
import ejb.UserFacade;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.ejb.EJB;
import javax.faces.application.FacesMessage;
import javax.faces.bean.ApplicationScoped;
import javax.faces.bean.ManagedBean;
import javax.faces.context.FacesContext;
import phoneThreads.PhoneThread;

/**
 *
 * @author Danilo
 */
@ManagedBean
@ApplicationScoped
public class AdminManagedBean {

    private User currentUser;
    private boolean serverStarted;
    private PhoneThread phoneThread;
    @EJB
    private UserFacade ufr;
    @EJB
    private ApplicationFacade apps;

    /** Creates a new instance of AdminManagedBean */
    public AdminManagedBean() {
    }

    /**
     * @return the currentUser
     */
    public User getCurrentUser() {
        String username = (String) FacesContext.getCurrentInstance().getExternalContext().getSessionMap().get("id");
        if (username != null) {
            if (currentUser != null) {
                return currentUser;
            }
            try {
                currentUser = ufr.find(username).clone();
            } catch (CloneNotSupportedException ex) {
                Logger.getLogger(AdminManagedBean.class.getName()).log(Level.SEVERE, null, ex);
            }
        } else {
            currentUser = null;
        }
        return currentUser;
    }
    

    public void serverManager() {        
        serverStarted = !isServerStarted();
        if (isServerStarted()) {
            // pokrenuti osluskivanje
            phoneThread = new PhoneThread();
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Server je pokrenut", null));
        } else {
            //zaustaviti osluskivanje
            phoneThread.interrupt();
            FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_INFO, "Server je zaustavljen", null));
        }
    }

    public String getValueForButton() {
        if (isServerStarted()) {
            return "Stopiraj server";
        }
        return "Pokreni server";
    }

    /**
     * @return the serverStarted
     */
    public boolean isServerStarted() {
        return serverStarted;
    }

    /**
     * @return the apps
     */
    public ApplicationFacade getApps() {
        return apps;
    }

    /**
     * @param apps the apps to set
     */
    public void setApps(ApplicationFacade apps) {
        this.apps = apps;
    }
}
